package com.ctvit.sjk.knowledge.model.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ctvit.sjk.knowledge.core.constant.KnowledgeConstant;
import com.ctvit.sjk.knowledge.core.controller.KnowledgeController;
import com.ctvit.sjk.knowledge.model.pojo.domain.TabModel;
import com.ctvit.sjk.knowledge.model.pojo.dto.ModelAddDTO;
import com.ctvit.sjk.knowledge.model.pojo.dto.ModelEditDTO;
import com.ctvit.sjk.knowledge.model.pojo.vo.ModelViewVO;
import com.ctvit.sjk.knowledge.model.service.ITabModelService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模型Controller
 *
 * @author heyingcheng
 * @date 2025/3/22
 */
@RestController
@RequestMapping("knowledge/model")
public class TabModelController extends KnowledgeController {

    private final ITabModelService tabModelService;

    public TabModelController(ITabModelService tabModelService) {
        this.tabModelService = tabModelService;
    }

    /**
     * 查询模型列表
     */
    @GetMapping
    public AjaxResult list(
            @RequestParam(required = false) String name,
            @RequestParam(value = "create_user", required = false) String createUser,
            @RequestParam(value = "permission_type", required = false) String permissionType,
            @RequestParam(value = "model_type", required = false) String modelType) {
        LambdaQueryWrapper<TabModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name), TabModel::getModelName, name);
        wrapper.eq(StringUtils.isNotBlank(createUser), TabModel::getCreateId, createUser);
        wrapper.eq(StringUtils.isNotBlank(permissionType), TabModel::getPermissionType, permissionType);
        wrapper.eq(StringUtils.isNotBlank(modelType), TabModel::getModelType, modelType);
        wrapper.orderByDesc(TabModel::getUpdateTime);

        List<TabModel> entities = tabModelService.list(wrapper);
        List<ModelViewVO> results = entities.stream().map(ModelViewVO::new).collect(Collectors.toList());

        return success(results);
    }

    /**
     * 新增模型
     */
    @Log(title = "模型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ModelAddDTO dto) {
        TabModel entity = new TabModel();
        entity.setModelId(IdWorker.getIdStr());
        entity.setModelName(dto.getName());
        entity.setModelType(dto.getModelType());
        entity.setMetadata(KnowledgeConstant.JSON_OBJECT_EMPTY);
        entity.setPermissionType(dto.getPermissionType());
        entity.setModelParamsForm(JSON.toJSONString(dto.getModelParamsForm()));
        entity.setCredential(JSON.toJSONString(dto.getCredential()));
        entity.setProviderCode(dto.getProvider());
        entity.setProviderModel(dto.getModelName());
        entity.setCreateId(CREATE_ID);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateId(CREATE_ID);
        entity.setUpdateTime(LocalDateTime.now());

        return toAjax(tabModelService.save(entity));
    }

    /**
     * 获取模型详细信息
     */
    @GetMapping("{id}")
    public AjaxResult get(@PathVariable String id) {
        TabModel entity = tabModelService.getById(id);
        return success(new ModelViewVO(entity));
    }

    /**
     * 修改模型
     */
    @Log(title = "模型", businessType = BusinessType.UPDATE)
    @PutMapping("{id}")
    public AjaxResult edit(@PathVariable String id, @RequestBody ModelEditDTO dto) {
        TabModel entity = new TabModel();
        entity.setModelId(id);
        entity.setModelName(dto.getName());
        entity.setPermissionType(dto.getPermissionType());
        entity.setCredential(JSON.toJSONString(dto.getCredential()));
        entity.setProviderModel(dto.getModelName());
        entity.setUpdateId(CREATE_ID);
        entity.setUpdateTime(LocalDateTime.now());

        return toAjax(tabModelService.updateById(entity));
    }

    /**
     * 获取模型参数设置信息
     */
    @GetMapping("{id}/model_params_form")
    public AjaxResult getModelParamsForm(@PathVariable String id) {
        TabModel entity = tabModelService.getById(id);
        return success(JSON.parseArray(entity.getModelParamsForm()));
    }

    /**
     * 修改模型参数设置信息
     */
    @Log(title = "模型", businessType = BusinessType.UPDATE)
    @PutMapping("{id}/model_params_form")
    public AjaxResult editModelParamsForm(@PathVariable String id, @RequestBody JSONArray modelParamsForm) {
        TabModel entity = new TabModel();
        entity.setModelId(id);
        entity.setModelParamsForm(JSON.toJSONString(modelParamsForm));

        return toAjax(tabModelService.updateById(entity));
    }

    /**
     * 删除模型
     */
    @Log(title = "模型", businessType = BusinessType.DELETE)
    @DeleteMapping("{id}")
    public AjaxResult remove(@PathVariable String id) {
        return toAjax(tabModelService.removeById(id));
    }

}
